/**
 * A global place for keeping a list of hangout paticipants
 */
var participants_ = [];

/**
 * A place to hold the user profiles
 **/
var profiles_ = {};

/**
 * Places lived,
 * String: number
 */
var places_ = {};

/**
 * Schools
 * String: number
 */
var schools_ = {};

/**
 * Employers
 * String: number
 */
var employers_ = {};

/**
 * Occupations
 * String: number
 */
var occupations_ = {};

/**
 * When hangout API is loaded, load G+ api
 */
var hangoutInit = function() {
  gapi.client.load('plus', 'v1', function() {
      console.log('G+ api loaded.');
      appInit(); });
  //gapi.client.setApiKey('AIzaSyC428LK6PpW8x8o4j3x5aqyD1tzzKDmui8');
  gapi.client.setApiKey('AIzaSyBgIaqlsFoOyrHgw7hagefH8zW3dt6zjtQ');
};

/**
 * When G+ api is loaded, really started the app init
 */
var appInit = function() {
  //Set up state change listener
  gapi.hangout.onParticipantsChanged.add(
      function(participantsChangedEvent) {
        updateParticipants(participantsChangedEvent);
    });

  updateAllParticipants();
};

var updateAllParticipants = function() {
  console.log('update all participants!');
  participants_ = gapi.hangout.getParticipants();
  getProfiles();
  var delayRender = setTimeout("render()", 2000);
};

var updateParticipants = function(participantChangedEvent) {
  console.log('participants changed!');
  participants_ = participantChangedEvent.participants;
  getProfiles();
  var delayRender = setTimeout("render()", 2000);
};

var getProfiles = function() {
  // clear the profiles;
  profiles_ = {};
  for(i = 0; i < participants_.length; ++i) {
    if (participants_[i].person && participants_[i].person.id) {
      var request = gapi.client.plus.people.get({'userId': participants_[i].person.id});
      request.execute(function(resp) {
          saveUserProfile(resp)
              });
    }
  }
};

/**
 * Save the profile returned by G+ api into a
 * global hash table, keyed by the user id
 */
var saveUserProfile = function(resp) {
  // resp is a people resource object
  id = resp.id;
  profiles_[id] = resp;
};

/**
 * Main render function
 */
var render = function() {
  collectFacts();

  var imgLinkUrlPrefix = 'http://maps.googleapis.com/maps/api/staticmap?size=195x150&sensor=false&markers=size:small|color:green|';
  var locationString = makeCleanLocationString();
  var mapImgLink = imgLinkUrlPrefix + locationString;
  var imageTag = $('<img src="' + mapImgLink + '" />');
  $('#pi').empty().append(imageTag);


  var ulDivPlaces = $('<ul></ul>');
  for(var place in places_) {
    ulDivPlaces.append($('<li>' + place + ' : ' + places_[place] + '</li>'));
  }
  $('#pt').empty().append('<div id="ptt" class="subcap"><p>Places the participants had been to:</p></div>')
  .append(ulDivPlaces);

  var ulDivWorks = $('<ul></ul>');
  for(var occupation in occupations_) {
    ulDivWorks.append($('<li>' + occupation + ' : ' +
                        occupations_[occupation] + '</li>'));
  }
  $('#work').empty().append('<div id="ott" class="subcap"><p>Occupations of the participants:</p></div>')
  .append(ulDivWorks);


  var ulDivSchools = $('<ul></ul>');
  for(var school in schools_) {
    ulDivSchools.append($('<li>' + school + ' : ' + schools_[school] + '</li>'));
  }
  $('#school').empty().append('<div id="stt" class="subcap"><p>Schools the participants went to:</p></div>')
  .append(ulDivSchools);

};

/**
 * Parse the participants inform and call into G+ api
 * to get the inform.
 * too bad there is no batch api to get user info
 */
var collectFacts = function() {
  // Clear the hash tables
  schools_ = {};
  employers_ = {};
  places_ = {};
  occupations_ = {};

  // Iterate the profiles, rely on the fact JS is single threaded
  for (var id in profiles_) {
    var orgName = '';
    var palces = '';
    // Parse orgnizations
    if (profiles_[id].organizations) {
      var orgLength = profiles_[id].organizations.length;
      for (var i = 0; i < orgLength; ++i) {
        var org = profiles_[id].organizations[i];
        orgName = org.name;
        if (orgName) {
          if (org.type == 'school'){
            setOrAddOne(schools_, orgName);
          }
          else if (org.type == 'work') {
            setOrAddOne(employers_, orgName);
            if (org.title) {
              setOrAddOne(occupations_, org.title);
            }
          }
        }
      }
    }

    // Parse places
    if (profiles_[id].placesLived){
      var placesLength = profiles_[id].placesLived.length;
      for (var i = 0; i < placesLength; ++i) {
        setOrAddOne(places_, profiles_[id].placesLived[i].value);
      }
    }
  }
};

/**
 * Utility function to set or add a "1" to a hash table
 */
var setOrAddOne = function(hashMap, key) {
  if (hashMap[key] == undefined){
    hashMap[key] = 1;
  }
  else {
    hashMap[key] += 1;
  }
};

/**
 * Return a clean string of
 * location1|location2|location3
 * Todo: more clean?
 */
var makeCleanLocationString = function() {
  cleanLocations = [];
  for (var location in places_) {
    cleanLocations.push(location);
  }
  return cleanLocations.join('|');
}

/**
 * A test function to test if the basic G+ API works
 */
var testGetPeople = function() {
  // Extrernal account is OK
  var request = gapi.client.plus.people.get({'userId': '113220668349795241439'});
  // plus Api can't find the user account from the internal G+
  // var request = gapi.client.plus.people.get({'userId': '103679899283654887386'});
  request.execute(function(resp) { console.log(resp); });
};

// register start point
gapi.hangout.onApiReady.add(hangoutInit);